package com.pandora.loan.home.web.advice;

import com.pandora.loan.common.util.*;
import com.pandora.loan.home.entity.Account;
import com.pandora.loan.home.exception.token.AccessTokenExpiredException;
import com.pandora.loan.home.exception.token.AccessTokenInvalidException;
import com.pandora.loan.home.exception.token.AccessTokenRequiredException;
import com.pandora.loan.home.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author developer
 */
public class AccessTokenVerifier extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AccountService accountService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    /**
     * 校验access_token
     *
     * @param accessToken access_token
     * @return String
     */
    private boolean checkAccessToken(String accessToken) {
        if (!StringUtils.isNotEmpty(accessToken)) {
            logger.error("No access_token...");
            throw new AccessTokenRequiredException();
        }
        String appId = JedisUtil.get(Constants.BUSINESS_REDIS_URL, StringUtils.getStrParam(Constants.ACCESS_TOKEN_KEY, accessToken));
        if (appId == null || "".equals(appId)) {
            logger.error("No app_id for accessToken {}", accessToken);
            throw new AccessTokenExpiredException();
        }
        Account account = accountService.getById(Long.parseLong(appId));
        if (account == null) {
            logger.error("No app_id in accounts for accessToken {}", accessToken);
            throw new AccessTokenInvalidException();
        }
        return true;
    }
}
